import json
import logging
from django.http import JsonResponse
from django.views import View
from django.core.paginator import Paginator
import traceback

from .models import MobileInfo, MonitorInfo, District
from big_screen.utils import tools as t, sys_setting as code
from big_screen.utils.paginator import page_request as pr
from BigScreen.task import set_black_broadcasting, set_bigscreen_chart as setChart
from .Serialization import serMobile, serMonitor, serUserRecord, serMobileNewLocation

errlog = logging.getLogger("Process")
logger = logging.getLogger('django')
bodylog = logging.getLogger("body")


# Create your views here.
# √
# 移动端名单
class ControlTextView(View):
    # √
    @classmethod
    def get(cls, request):
        """
        获取移动端信息
        :param request:
        :return:
        """
        # if request.user.is_authenticated():
        # ---------------- 获取设备信息 ---------------------
        s = serMobile()
        mobile_list = s.get_info()
        # ---------------- 分页 -----------------------------
        ret = request.GET  # 分页信息
        limit, page = pr(ret)
        pagionitor = Paginator(mobile_list, limit)
        content = list()
        for data in pagionitor.page(eval(page)):
            content.append(data)
        # ----------------- 组织数据 ------------------------
        con = {
            "mobile_length": pagionitor.count,
            "data": content
        }
        return JsonResponse(con)

    # √
    @classmethod
    def post(cls, request):
        """
        添加移动端
        :param request:
        :return:
        """
        # try:
        # if request.user.is_authenticated():
        # ------------------ 获取设备信息 -------------------
        ret = json.loads(request.body.decode())
        # ------------------ 保存设备 -----------------------
        mon = serMonitor()
        s = serMobile()
        con = s.insert_info(**ret)
        return JsonResponse(con)
        # except Exception:
        # traceback.print_exc()

    # √
    @classmethod
    def delete(cls, request):
        """
        删除移动端
        :param request:
        :return:
        """
        ret = eval(request.body.decode())
        s = serMobile()
        ret["id"] = s.table.get(mobile=ret.pop("mobile")).id
        con = s.delete_info(ret)
        return JsonResponse(con)

    # √
    @classmethod
    def patch(cls, request):
        """
        修改设备信息
        :param request:
        :return:
        """
        s = serMobile()
        mon = serMonitor()
        ret = eval(request.body.decode())
        ret["id"] = s.table.get(mobile=ret.pop("mobile")).id
        con = s.update_info(ret)
        return JsonResponse(con)


# √
# 移动端位置
class MobileLocationView(View):
    # √
    @classmethod
    def get(cls, request, mobile):
        """
        根据移动端id获取最近10个位置
        :param mobile:
        :param request:
        :return:
        """
        ret = dict(request.GET)
        ret["mobile"] = mobile
        ret["s_time"] = ret["s_time"][0]
        ret["e_time"] = ret["e_time"][0]
        #
        s = serMobileNewLocation()
        content = s.select_info(ret)
        con_list = list()
        for con in content:
            if con["lnglat"] is "x,x":
                continue
            else:
                con["lnglat"] = con["lnglat"].split(",")
                con_list.append(con)
        con = {
            "code": code.STATUSCODE_SUCCESS,
            "msg": "success",
            "data": con_list
        }
        return JsonResponse(con)

    @classmethod
    def post(cls, request):
        # try:
        # ------------- 接收 -------------------
        ret = eval(request.body.decode())
        # ------------- 序列化器 ----------------
        s = serMobileNewLocation()
        # -------------- 查询 -------------------
        content = s.select_info(ret)
        # print("before remove: ")
        # print(content)
        content = list(map(lambda info: info.split(","), content))
        content_list = list()
        for con in content:
            if con not in content_list:
                content_list.append(con)
        # print("qu chong:")
        # print(content_list)
        if ['x', 'x'] in content_list:
            content_list.remove(['x', 'x'])
        if ['0.0', '0.0'] in content_list:
            content_list.remove(['0.0', '0.0'])
        con = {
            "code": code.STATUSCODE_SUCCESS,
            "msg": "success",
            "data": content_list
        }
        return JsonResponse(con)
        # except Exception:
        # traceback.print_exc()


# √
# 表单下拉框信息
class FromSelectView(View):
    # √
    @classmethod
    def get(cls, request):
        """
        表单信息获取
        :param request:
        :return:
        """
        ret = request.GET
        errlog.info(ret)
        # 地区
        district_id = District.objects.get(id=code.SYS_DISTRICT)
        pla_obj_list = District.objects.filter(superior=district_id.id, is_district=1).values("name", "id")
        p_list_data = list(pla_obj_list)
        p_list = list()
        sys_district = District.objects.get(id=code.SYS_DISTRICT).name
        sys_dis_info = {
            "name": sys_district,
            "id": 0
        }
        p_list.append(sys_dis_info)
        p_list.extend(p_list_data)
        # 检测人员
        mon_obj_list = MonitorInfo.objects.filter(is_delete=0).values("idcard", "name")
        mon_list = list(mon_obj_list)
        # 手机信息
        mob_obj = MobileInfo.objects.filter(is_delete=0).values("mobile", "name")
        mob_list = list(mob_obj)
        # 台站信息
        dis_obj = District.objects.filter(is_district=0).values("name", "id")
        dis_list = list(dis_obj)
        con = {
            "place_info": p_list,
            'monitor_info': mon_list,
            "mobile_info": mob_list,
            "district_info": dis_list
        }
        return JsonResponse(con)


# traceback.print_exc()

# √
class MonitorView(View):
    # √
    @classmethod
    def get(cls, request):
        """
        获取检测人员信息
        :param request:
        :return:
        """
        # try:
        # if request.user.is_authenticated():
        # ---------------------- 获取参数 -----------------------
        ret = request.GET
        limit, page = pr(ret)
        # ---------------------- 序列化器 ------------------------
        s = serMonitor()
        # --------------------- 手机端获取打卡名单 ----------------
        if "time" in ret.keys():
            mobile = ret.get("phoneid")
            content = s.get_by_mobile(mobile)
            count = len(content)
        # ---------------- 页面数据 ------------------
        else:
            content = s.get_info_userecord()
            # # --------------------- 分页 ----------------------------
            paginator = Paginator(content, limit)
            content = list()
            for info in paginator.page(page):
                content.append(info)
            count = paginator.count
        # # ---------------------- 组织数据返回 -------------------
        con = {
            'data': content,
            'count': count,
            "code": code.STATUSCODE_SUCCESS,
            "msg": "ok"
        }
        return JsonResponse(con)
        # except Exception:
        # traceback.print_exc()

    # √
    @classmethod
    def post(cls, request):
        """
        添加检测人员信息
        :param request:
        :return:
        """
        # if request.user.is_authenticated():
        ret = eval(request.body.decode())
        s = serMonitor()
        con = s.insert_info(**ret)
        return JsonResponse(con)

    # √
    @classmethod
    def delete(cls, request):
        """
        删除检测人员信息
        :param request:
        :return:
        """
        ret = eval(request.body.decode())
        s = serMonitor()
        ret["id"] = s.table.get(idcard=ret.pop("idcard")).id
        con = s.delete_info(ret)
        return JsonResponse(con)

    # √
    @classmethod
    def patch(cls, request):
        """
        修改检测人员信息
        :param request:
        :return:
        """
        s = serMonitor()
        ret = eval(request.body.decode())
        ret["id"] = s.table.get(idcard=ret.pop("idcard")).id
        con = s.update_info(ret)
        return JsonResponse(con)


class ChangeSysTimeRangeView(View):
    # √
    @classmethod
    def get(cls, request):
        """
        修改系统配置
        :param request:
        :return:
        """

        if request.user.is_authenticated():
            s = t.setting()
            timerange = s.get_timerange()
            info = {
                'chart': s.chart_selectcycle,
                'massmark': s.massmark_selectcycle,
                'isworking': s.isworking_selectcycle
            }
            return JsonResponse({'code': code.STATUSCODE_SUCCESS, 'msg': '获取成功', 'data': timerange, 'info': info})

    @classmethod
    def post(cls, request):
        """
        修改黑广播显示时间范围
        :param request:
        :return:
        """

        if request.user.is_authenticated():
            ret = eval(request.body.decode())
            s = t.setting()
            # 验证
            # 正则
            for k, v in ret.items():
                try:
                    v = int(v)
                except ValueError:
                    return "请输入正整数"
                if k != 'timeRange':
                    msg = s.set(k, v)
                    con = {
                        'code': code.STATUSCODE_SUCCESS,
                        'msg': msg
                    }
                    return JsonResponse(con)
            try:
                num = int(ret['timeRange'])
            except Exception as e:
                logger.warning(e)
                con = {
                    'code': code.STATUSCODE_UNSUCCESS,
                    'msg': '数据保存失败'
                }
                return JsonResponse(con)
            if num > 720:
                return JsonResponse({'msg': '设置区间为[5,720]!'})
            if num < 5:
                return JsonResponse({'msg': '设置区间为[5,720]!'})
            try:
                s.save_timeRange(ret['timeRange'])
            except Exception as e:
                logger.info(repr(e))
                con = {
                    'code': code.STATUSCODE_UNSUCCESS,
                    'msg': '数据保存失败'
                }
                return JsonResponse(con)
            con = {
                'code': code.STATUSCODE_SUCCESS,
                'msg': 'ok'
            }
            set_black_broadcasting.delay()
            setChart.delay()
            return JsonResponse(con)


# √
class TimeinfoView(View):
    # √
    @classmethod
    def get(cls, request):
        if request.user.is_authenticated():
            s = t.setting()
            diff = s.get_datediff()
            con = {'diff': diff}
            return JsonResponse(con)


# √
class UseRecord(View):
    # √
    @classmethod
    def get(cls, request):
        """
        查询手机使用记录
        """
        ret = request.GET
        limit, page = pr(ret)
        # -------------- 序列化器 ----------------
        s = serUserRecord()
        # --------------- 检索 --------------------
        content = s.select_info(ret)
        # content = s.get_info()
        # # -------------------- 分页 -------------------
        paginator = Paginator(content, limit)
        result = list()
        for info in paginator.page(page):
            result.append(info)
        count = paginator.count
        # # -------------------- 组织数据返回 -----------------
        con = {
            "count": count,
            "data": result,
            "code": code.STATUSCODE_SUCCESS,
            "msg": "success"
        }
        # con = code.con
        return JsonResponse(con)

    # √
    @classmethod
    def post(cls, request):
        """
        上传使用记录
        """
        # try:
        # ------------------- 准备 -----------------------
        # ********** 请求 *************
        ret = eval(request.body.decode())
        bodylog.info(ret)
        # ********** 序列化器 ***********
        mob = serMobile()
        mon = serMonitor()
        s = serUserRecord()
        # -------------------- 组织数据 ---------------------
        mobile_id = mob.table.get(mobile=ret.pop("phoneid")).id
        monitor_id = mon.table.get(idcard=ret.pop("idcard")).id
        # ********* 使用记录 ************
        insert_dict = dict()
        insert_dict["mobile_id"] = mobile_id
        insert_dict["monitor_id"] = monitor_id
        insert_dict["time"] = t.get_time(ret.get("time"))
        # ******** 设备使用人员 ***********
        update_dict = dict()
        update_dict["id"] = mobile_id
        update_dict["monitor_id"] = monitor_id
        # -------------------- 处理 --------------------------
        con = s.insert_info(**insert_dict)
        mob.update_info(update_dict)
        # -------------------- 返回 ---------------------------
        return JsonResponse(con)
        # except Exception:
        # traceback.print_exc()


def select_userecord(request):
    """
    检索使用记录
    :param request:
    :return:
    """
    ret = eval(request.GET)
    return JsonResponse(code.con)
